<?php
namespace app\admin\controller;

use app\common\controller\AdminController;
use think\facade\Db;
use think\facade\View;
use think\facade\Config;
use think\Facade\Request;
use think\Facade\Session;
use app\admin\model\sys\AuthRule;
use helper\Menu;


class Base extends AdminController
{
    protected $menus;
    public function initialize()
    {
        parent::initialize();
        $this->menus = new Menu();

        $controller = \think\facade\Request::controller();
		$action = \think\facade\Request::action();
		define('ACTION_NAME', $action);
		$this->authCheck();
        $keyArr = getCustomSys();


        $cate = AuthRule::where('menu_status',1)->order('sort asc')->select()->toArray();
        $menus = $this->menus->menu($cate);

        View::assign('menus',json_encode($menus,320));

        View::assign('sys',$keyArr);

    }
    public function logout(){
        session('admin',null);
        return redirect(url('login/index'));
    }
    /**
     * 验证权限
     */
    public function authCheck(){

        $allow = [
            'admin/index/index',
            'admin/index/main',
            'admin/index/clearData',
            'admin/index/logout',
            'admin/login/password',
            'admin/index/menus',
        ];
        $adminRules = [];
        $route = app('http')->getName().'/'.strtolower(Request::controller()).'/'.(Request::action());
        if(session('admin.id')!==1){
            $this->hrefId = Db::name('auth_rule')->where('href',$route)->value('id');
            //当前管理员权限
            $rules=Db::name('auth_group')
                ->where('id',session('admin.group_id'))
                ->value('rules');
            //用户权限规则id
            $adminRules = explode(',',$rules);
            // 不需要权限的规则id;
            $noruls = AuthRule::where('auth_open',1)->column('id');
            $adminRules = array_merge($adminRules,$noruls);
            if($this->hrefId){
                // 不在权限里面，并且请求为post
                if(!in_array($this->hrefId,$adminRules)){
                    $this->error(lang('permission denied'));
                    exit();
                }
            }else{
                if(!in_array($route,$allow)) {
                    $this->error(lang('permission denied'));
                    exit();
                }

            }
        }
        return $adminRules;

    }
}
